package com.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * Spring 多环境支持的配置类
 * 实现多环境数据源的切换
 *
 * 加了环境标识@Profile的bean，只有激活某种环境才能注入
 * 不明确激活某种环境，默认环境是default，没有加@Profile注解的bean都会加载
 *
 * 如何激活环境
 *      1.vm option 添加 -Dspring.profiles.active=dev
 *      2.无参构造器
 * @Profile 也可以写在配置类上，满足环境整个配置类才生效
 */
@Configuration
@PropertySource("classpath:db.properties")
public class SpringConfig4 {

    @Bean
    @Profile("test")
    public DataSource dataSourceTest(@Value("${db.username}") String username,
                                     @Value("${db.password}") String password,
                                     @Value("${db.url}") String url,
                                     @Value("${db.driverClass}") String driverClass)  {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        return dataSource;
    }


    @Bean
    @Profile("dev")
    public DataSource dataSourceDev(@Value("${db.username}") String username,
                                    @Value("${db.password}") String password,
                                    @Value("${db.url}") String url,
                                    @Value("${db.driverClass}") String driverClass)  {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        return dataSource;
    }

    @Bean
    @Profile("prod")
    public DataSource dataSourceProd(@Value("${db.username}") String username,
                                     @Value("${db.password}") String password,
                                     @Value("${db.url}") String url,
                                     @Value("${db.driverClass}") String driverClass) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        return dataSource;
    }


}



